package com.octant.testipc;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.tuya.smart.android.user.api.ILogoutCallback;
import com.tuya.smart.android.user.api.IWhiteListCallback;
import com.tuya.smart.android.user.bean.User;
import com.tuya.smart.android.user.bean.WhiteList;
import com.tuya.smart.home.sdk.TuyaHomeSdk;
import com.tuya.smart.sdk.api.IDevListener;
import com.tuya.smart.sdk.api.IResultCallback;
import com.tuya.smart.sdk.api.ITuyaDevice;
import com.tuya.smart.sdk.bean.DeviceBean;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, HomeUtil.HomeUtilListener {

    private TextView tv_user_name,tv_home_name;
    private Button btn_login,btn_register,btn_logout,btn_add_device;
    private RecyclerView recyclerview_device;

    private Context mContext;

    List<DeviceBean> deviceList = new ArrayList<>();
    List<ITuyaDevice> tuyaDeviceList = new ArrayList<>();
    DeviceAdapter deviceAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = MainActivity.this;
        initViews();
        HomeUtil.getInstance().listener = this;
    }

    private void initViews() {
        tv_user_name = findViewById(R.id.tv_user_name);
        btn_login = findViewById(R.id.btn_login);
        btn_register = findViewById(R.id.btn_register);
        btn_logout = findViewById(R.id.btn_logout);
        tv_home_name = findViewById(R.id.tv_home_name);
        recyclerview_device = findViewById(R.id.recyclerview_device);
        btn_add_device = findViewById(R.id.btn_add_device);

        tv_user_name.setOnClickListener(this);
        btn_login.setOnClickListener(this);
        btn_register.setOnClickListener(this);
        btn_logout.setOnClickListener(this);
        btn_add_device.setOnClickListener(this);

        recyclerview_device.setLayoutManager(new LinearLayoutManager(this));
        deviceAdapter = new DeviceAdapter(mContext,deviceList);
        deviceAdapter.setItemClickListener(new DeviceAdapter.ItemClickListener() {
            @Override
            public void onClick(int pos) {
                Intent intent = new Intent(mContext,DeviceDetailActivity.class);
                intent.putExtra("devId",deviceList.get(pos).devId);
                startActivity(intent);
            }

            @Override
            public void onRemove(int pos) {
                ITuyaDevice mDevice = TuyaHomeSdk.newDeviceInstance(deviceList.get(pos).devId);
                mDevice.removeDevice(new IResultCallback() {
                    @Override
                    public void onError(String errorCode, String errorMsg) {
                        mDevice.onDestroy();
                        Toast.makeText(mContext,
                                "移除设备失败"+errorCode+","+errorMsg,
                                Toast.LENGTH_SHORT).show();
                        HomeUtil.getInstance().listHome();
                    }

                    @Override
                    public void onSuccess() {
                        mDevice.onDestroy();
                        Toast.makeText(mContext,
                                "移除设备成功",
                                Toast.LENGTH_SHORT).show();
                        HomeUtil.getInstance().listHome();
                    }
                });
            }
        });
        recyclerview_device.setAdapter(deviceAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkAccount();
        checkHome();
    }

    private void checkAccount(){
        if (TuyaHomeSdk.getUserInstance().isLogin()) {
            btn_login.setVisibility(View.GONE);
            btn_register.setVisibility(View.GONE);
            btn_logout.setVisibility(View.VISIBLE);
            User user = TuyaHomeSdk.getUserInstance().getUser();
            tv_user_name.setText(user.getUsername());

        }else {
            btn_login.setVisibility(View.VISIBLE);
            btn_register.setVisibility(View.VISIBLE);
            btn_logout.setVisibility(View.GONE);
            tv_user_name.setText("请先登录");
        }
    }

    private void checkHome(){
        if (TuyaHomeSdk.getUserInstance().isLogin()) {
            if (HomeUtil.getInstance().homeBean == null) {
                HomeUtil.getInstance().initHome();
            }else {
                tv_home_name.setText(""+HomeUtil.getInstance().homeBean.getName());
                List<DeviceBean> tempList = HomeUtil.getInstance().homeBean.getDeviceList();
                if (deviceList.equals(tempList) == false) {
                    for (int i=0; i<tuyaDeviceList.size(); i++){
                        tuyaDeviceList.get(i).unRegisterDevListener();
                    }
                    tuyaDeviceList.clear();
                    deviceList.clear();
                    deviceList.addAll(tempList);
                    for (int i=0; i<deviceList.size(); i++){
                        ITuyaDevice tuyaDevice = TuyaHomeSdk.newDeviceInstance(deviceList.get(i).devId);
                        tuyaDevice.registerDevListener(devListener);
                        tuyaDeviceList.add(tuyaDevice);
                    }
                    deviceAdapter.notifyDataSetChanged();
                }
            }
        }else {
            tv_home_name.setText("");
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_user_name:{

            }break;
            case R.id.btn_login:{
                Intent intent = new Intent(MainActivity.this,LoginActivity.class);
                startActivity(intent);
            }break;
            case R.id.btn_register:{
                Intent intent = new Intent(MainActivity.this,RegisterActivity.class);
                startActivity(intent);
            }break;
            case R.id.btn_logout:{
                ILogoutCallback callback = new ILogoutCallback() {
                    @Override
                    public void onSuccess() {
                        Toast.makeText(mContext,
                                "Logout success",
                                Toast.LENGTH_SHORT).show();
                        checkAccount();
                    }
                    @Override
                    public void onError(String code, String error) {
                        Toast.makeText(mContext,
                                "code: " + code + "error:" + error,
                                Toast.LENGTH_SHORT).show();
                        checkAccount();
                    }
                };
                TuyaHomeSdk.getUserInstance().touristLogOut(callback);
            }break;
            case R.id.btn_add_device:{
                if (TuyaHomeSdk.getUserInstance().isLogin()) {
                    Intent intent = new Intent(mContext,DeviceConfigQrcodeActivity.class);
                    startActivity(intent);
                }else {
                    Toast.makeText(mContext, "请先登录账号", Toast.LENGTH_SHORT).show();
                }
            }break;
        }
    }

    @Override
    public void onHomeStateChange(int state) {
        if (state == HomeUtil.HOME_STATE_GET_HOME_DETAIL_SUCCESS){
            tv_home_name.setText(""+HomeUtil.getInstance().homeBean.getName());
            deviceList.clear();
            deviceList.addAll(HomeUtil.getInstance().homeBean.getDeviceList());
            deviceAdapter.notifyDataSetChanged();
        }
    }

    IDevListener devListener = new IDevListener() {

        /**
         * DP 数据更新
         *
         * @param devId 设备 ID
         * @param dpStr 设备发生变动的功能点，为 JSON 字符串，数据格式：{"101": true}
         */
        @Override
        public void onDpUpdate(String devId, String dpStr) {
        }

        /**
         * 设备移除回调

         *
         * @param devId 设备id

         */
        @Override
        public void onRemoved(String devId){
            Toast.makeText(mContext, "设备已经被移除", Toast.LENGTH_SHORT).show();
            HomeUtil.getInstance().listHome();
        }

        /**
         * 设备上下线回调。如果设备断电或断网，服务端将会在3分钟后回调到此方法。

         *
         * @param devId  设备 ID
         * @param online 是否在线，在线为 true

         */
        @Override
        public void onStatusChanged(String devId, boolean online){
            deviceAdapter.notifyDataSetChanged();
        }

        /**
         * 网络状态发生变动时的回调

         *
         * @param devId  设备 ID
         *  @param status 网络状态是否可用，可用为 true

         */
        @Override
        public void onNetworkStatusChanged(String devId, boolean status){
        }

        /**
         * 设备信息更新回调

         *
         * @param devId  设备 ID

         */
        @Override
        public void onDevInfoUpdate(String devId){
        }

    };


}